import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_blue/flutter_blue.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:hex/hex.dart';
import 'package:jxchmz/%E8%93%9D%E7%89%99/BleManager.dart';
import 'package:jxchmz/%E8%93%9D%E7%89%99/ScanDevice.dart';
import 'package:jxchmz/API/%E8%BF%9B%E5%88%B6%E8%BD%AC%E6%8D%A2/HexGo.dart';
import 'package:jxchmz/BleModel.dart';
import 'package:jxchmz/Getx%E5%B7%A5%E5%85%B7/GetxTools.dart';
import 'package:jxchmz/Getx%E5%B7%A5%E5%85%B7/KSProgressDialog.dart';

class DeviceConnect extends StatefulWidget {
  @override
  _DeviceConnectState createState() => new _DeviceConnectState();
}

class _DeviceConnectState extends State<DeviceConnect> {
  //是否扫描标识
  var IsScan = false;
    BluetoothCharacteristic? characteristicForFFF1;

   BluetoothCharacteristic? characteristicForFFF2;

  late BluetoothCharacteristic _characteristicForFFF3;

  late BluetoothCharacteristic _characteristicForFFF4;

  late BluetoothDevice device;

  //存放蓝牙设备列表i
  List<BluetoothDevice> deviceList = [];

  //去重使用的数组
  List<DeviceIdentifier> deviceIdList = [];

  //是否连接
  var IsConnect = false;
  GetStorage getStorage = new GetStorage();


//页面加载完成时
  @override
  void initState()  {
    // TODO: implement initState
    super.initState();
   Future.delayed(Duration.zero,() async {
     //获取连接池
     List<BluetoothDevice>? devideList =await  BleManager.instance.getConnectedDevices();
     if (devideList!.length>0) {
       IsConnect =true;
       print("连接状态:$IsConnect");
         print("当前连接池设备:$devideList");
         device = devideList[0];
       setState(() {
       });
     }else{
       IsConnect =false;
     }
   });

  }

  ///页面卸载
  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
   if(IsConnect){

     //取消监听
     characteristicForFFF1!.setNotifyValue(false);
     BleManager.instance.CancelListen();
     print("取消监听");
     // print("服务:${BleModel().BletoothCharacteristicFFF1}");
   }
  }

  ///当 State 被暂时从视图树中移除时，会调用这个方法，同时页面切换时，也会调用。
  @override
  void deactivate() {
    // TODO: implement dispose
    super.deactivate();
  }

  ///在 initState() 之后调用，当 State 对象的依赖关系发生变化时，该方法被调用，初始化时也会调用。
  @override
  void didChangeDependencies() {
    // TODO: implement didChangeDependencies
    super.didChangeDependencies();
  }

  // TODO: add state variables and methods
  @override
  Widget build(BuildContext context) {
    // TODO: add widget build method
    return Scaffold(
        backgroundColor: Colors.white,
        appBar: AppBar(
          backgroundColor: Colors.white,
          title: Text(
            "Deviceconnection".tr,
            style: TextStyle(fontSize: 15, color: Colors.black),
          ),
          centerTitle: true,
          elevation: 0,
          iconTheme: IconThemeData(
            color: Colors.black, //修改颜色
          ),
        ),
        body: Column(
          children: [
            //蓝牙列表
            //蓝牙设备详情界面
            IsConnect
                ? Container(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Image.asset(
                    "Image/BleDevice.jpg",
                    width: MediaQuery
                        .of(context)
                        .size
                        .width - 30,
                    height: 300,
                  ),
                  Container(
                    child: Text(
                      "Bluetoothname".tr+":${device.name}",
                      style: TextStyle(fontSize: 20),
                    ),
                  ),
                  Container(
                    child: Text(
                      "deviceId:${device.id}",
                      style: TextStyle(fontSize: 20),
                    ),
                  ),
                ],
              ),
            )
                : Expanded(
              child: ListView.builder(
                itemCount: deviceList.length,
                itemBuilder: (context, index) {
                  return Container(
                    padding: EdgeInsets.all(15),
                    child: ListTile(
                      leading: Container(
                        width: 50,
                        height: 50,
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(50),
                          image: DecorationImage(
                              image: new AssetImage(
                          "Image/${deviceList[index].name.contains("RFID") ? 'BleDevice' : 'defalueBle'}.jpg"),
                              fit: BoxFit.cover),
                        ),
                      ),
                      title: Text("${deviceList[index].name.length <= 0 ? "Unknowndevice".tr : deviceList[index].name}"),
                      subtitle: Text("deviceId：${deviceList[index].id}"),
                      trailing:GestureDetector(
                        child: Container(
                          child: Column(
                            children: [
                              Image.asset("Image/yuechi.png",width: 30,height: 30,color: Color(0xff4990e2),),
                              Expanded(child: Text(
                                "connect".tr,
                                style: TextStyle(color: Color(0xff4990e2)),
                              )),
                            ],
                          ),
                        ),
                        onTap: (){
                              if (IsScan) {
                                IsScan = false;
                              }
                              setState(() {});
                              device = deviceList[index];
                              KSProgressDialog().LoadingToast("Connecting".tr, context);
                              //选择连接
                              Connect(device);
                        },
                      )
                      // MaterialButton(
                      //   // minWidth: 30,
                      //
                      //   onPressed: () {
                      //     if (IsScan) {
                      //       IsScan = false;
                      //     }
                      //     setState(() {});
                      //     device = deviceList[index];
                      //     KSProgressDialog().LoadingToast("Connecting".tr, context);
                      //     //选择连接
                      //     Connect(device);
                      //   },
                      //   color: Color(0xff4990e2),
                      // ),
                    ),
                  );
                },
              ),
            ),
            Container(
              height: 15,
            ),
            Container(
              padding: EdgeInsets.all(15),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  !IsConnect
                      ? MaterialButton(
                    minWidth: MediaQuery
                        .of(context)
                        .size
                        .width - 30,
                    child: Text(
                      IsScan ? "停止扫描".tr : "TapScanBluetooth".tr,
                      style: TextStyle(color: Colors.white),
                    ),
                    onPressed: () {
                      if (!IsScan) {
                        IsScan = true;
                        deviceIdList = [];
                        deviceList = [];
                        // ScanDevice().StarScan();
                        BleManager.instance.startScan(scanResultHandler, timeout: 10);
                      } else {
                        IsScan = false;

                        // ScanDevice().StopScan();
                        BleManager.instance.stopScan();
                      }
                      setState(() {});
                    },
                    color: IsScan ? Colors.red : Color(0xff4990e2),
                  )
                      : MaterialButton(
                    minWidth: MediaQuery
                        .of(context)
                        .size
                        .width - 30,
                    child: Text(
                      "Disconnect".tr,
                      style: TextStyle(color: Colors.white),
                    ),
                    onPressed: () {
                      DisConnect();
                    },
                    color: Colors.red,
                  ),
                ],
              ),
            ),
            Container(
              height: 15,
            ),
          ],
        ));
  }

  //扫描结果监听
  Future<void> scanResultHandler(List<ScanResult>? results) async {
    print('results ====> ${results}');
    for (ScanResult r in results!) {
      print('${r.device.name} found! rssi: ${r.rssi}');
      if (r.advertisementData.serviceUuids.length > 0) {
        //添加到设备列表
        if (!deviceIdList.contains(r.device.id)) {
          print("不同的id");
          deviceIdList.add(r.device.id);
          deviceList.add(r.device);
          setState(() {});
        }
      }
    }
  }

  //连接设备
  void Connect(device) {
    print("开始连接设备:${device}");
    BleManager.instance.connectDevice(device).then((e) {
      _discoverServices(device);

    });
  }

  //扫描设备服务
  _discoverServices(device) async {
    List<BluetoothService> services = await BleManager.instance.deviceToDiscoverServices(device);

    print("+++++++$services");
    if (services == null) return;
    services.forEach((service) async {
      // do something with service
      print("uuid=${service.uuid}  deviceId=${service.deviceId}");
      print("---service is fff0---");

      var characteristics = service.characteristics;
      for (BluetoothCharacteristic c in characteristics) {
        // log("----BluetoothCharacteristic-->$c");
        print("----BluetoothCharacteristicUUID-->${c.uuid}");
        if (c.uuid.toString().contains("fff1")) {
          print("is fff1:${c.uuid.toString()}");
          characteristicForFFF1 = c;
          BleModel.BletoothCharacteristicFFF1 = characteristicForFFF1;
          // await Future.delayed(const Duration(seconds: 1));
          // _characteristicFFF4SetNotify();
        } else if (c.uuid.toString().contains("fff2")) {
          print("is fff2:${c.uuid.toString()}");
          characteristicForFFF2 = c;
          BleModel.BletoothCharacteristicFFF2 = characteristicForFFF2;
          // _characteristicFFF4SetNotify();
        }
      }
    });

    KSProgressDialog().CloseLoading();
    print("FFF1:$characteristicForFFF1");
    print("FFF2:$characteristicForFFF2");
    if (characteristicForFFF1 != null&&characteristicForFFF2!=null) {
      GetxTools().SuccessToast("Theconnectionwassuccessful".tr);
      IsConnect = true;
      //将是否连接表示保存本地

      getStorage.write("IsConnect",IsConnect);
      print("本地蓝牙数据:${getStorage.read("IsConnect")}");
      print("本地服务:${ BleModel.BletoothCharacteristicFFF1}");
//监听蓝牙连接状态
      BleConnectState();
    } else {
      GetxTools().ErrorToast("Connectionfailed".tr);
      IsConnect = false;
    }
    setState(() {});
  }

//  断开蓝牙
  void DisConnect() {
if(IsConnect){
  BleManager.instance.disconnectDevice(device).then((value) {
    print("disconnected !!");
    getStorage.remove("IsConnect");
    IsConnect = false;
    GetxTools().ErrorToast("Theconnectionhasbeendisconnected".tr);
    //重新搜索蓝牙设备
    // deviceList = [];
    // deviceIdList = [];
    // BleManager.instance.startScan(scanResultHandler, timeout: 10);
    setState(() {});
  });
}

  }

//监听特征上报数据
  _characteristicFFF4SetNotify() async {
    await characteristicForFFF1!.setNotifyValue(true);
    // ignore: missing_return
    BleManager.instance.listenCharacteristicValue(characteristicForFFF1!, (data) async {
      print("object=>>>>>>$data");
      if (data == null) {
        print("data=null>>>>>>");
        return;
      }
      //解析蓝牙数据，转为十六进制
      String DataHex =await _BleDataCallback(data);
      if(!DataHex.contains("f1,03,02")){
        //这里面写调用逻辑
      }else{
        //接受心跳数据，并发送数据，防止盘点拍关机
        // WriteBle([0xf1,0x03,0x02,0x63,0xa7]);
      }
    });
  }

  //监听蓝牙连接状态
  BleConnectState(){
   device.state.listen((event) {
     BluetoothDeviceState BleState = event;
     print("连接状态:${BleState.toString()}");
     if(BleState == BluetoothDeviceState.disconnected){
       if(IsConnect){
         print("断开");
         //断开连接
         DisConnect();
       }
     }
   });
  }

//  发送请求
  void WriteBle(WritData) {
    print("发送的蓝牙数据:${WritData}");
    BleManager.instance.characteristicToWriteValue(characteristicForFFF2!, WritData).then((value) => print("write result:$value"));
  }

//  读取设备的信息
  void ReadDeviceMessage() {
    print("设置读取设备信息");
    BleManager.instance.characteristicToReadValue(characteristicForFFF1!).then((value) {
      print("fff2 value=$value");
    });
  }

//解析蓝牙数据
  _BleDataCallback(value) async {
    List data = [];
    for (var i = 0; i < value.length; i++) {
      String dataStr = value[i].toRadixString(16);
      if (dataStr.length < 2) {
        dataStr = "0" + dataStr;
      }
      String dataEndStr =  dataStr;
      data.add(dataEndStr);
    }
    print("我是蓝牙返回数据 - ${data.join(",")}");
    return data.join(",");
  }

  //校验位
  int checkSum(List<int> buffer) {
    int sum = 0;
    for (int i = 0; i < buffer.length; i++) {
      sum += buffer[i];
    }
    sum = (~sum) + 1;
    return sum;
  }


}
